import { eq } from 'drizzle-orm'
import { rolesTable } from '~~/server/db/schema/role'
import { db } from '~~/server/db'

export default defineEventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'))

  if (!id || isNaN(id)) {
    throw createError({
      statusCode: 400,
      message: '角色ID格式错误'
    })
  }

  try {
    // 检查角色是否存在
    const [existingRole] = await db.select().from(rolesTable).where(eq(rolesTable.id, id)).limit(1)

    if (!existingRole) {
      throw createError({
        statusCode: 404,
        message: '角色不存在'
      })
    }

    // 使用事务删除角色及相关数据
    await db.transaction(async (tx) => {
      // 删除角色
      await tx.delete(rolesTable).where(eq(rolesTable.id, id))
    })

    return {
      message: '角色删除成功',
      data: true
    }
  } catch (error: any) {
    if (error.statusCode === 404) {
      throw error
    }

    console.error('Delete role error:', error)
    throw createError({
      statusCode: 500,
      message: '删除角色失败'
    })
  }
})
